package ltd.hxya.novel.crawl.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import ltd.hxya.novel.common.constant.redis.RedisConstant;
import ltd.hxya.novel.common.utils.RedisUtils;
import ltd.hxya.novel.crawl.bean.CrawlVo;
import ltd.hxya.novel.crawl.entity.CrawlRule;
import ltd.hxya.novel.crawl.mapper.CrawlRuleMapper;
import ltd.hxya.novel.crawl.service.ICrawlRuleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author hty
 * @since 2022-10-16
 */
@Service
public class CrawlRuleServiceImpl extends ServiceImpl<CrawlRuleMapper, CrawlRule> implements ICrawlRuleService {

    @Autowired
    private RedisUtils redisUtils;

    @Override
    public void updateAndAddCrawlRule(CrawlVo crawlVo) {
        QueryWrapper<CrawlRule> crawlRuleQueryWrapper = new QueryWrapper<>();
        crawlRuleQueryWrapper.eq("source_id",crawlVo.getId());
        CrawlRule crawlRule = this.baseMapper.selectOne(crawlRuleQueryWrapper);
        //如果当前数据库中没有该爬虫规则，则添加一个新的爬虫规则，如果有，则修改该爬虫规则
        if (ObjectUtils.isEmpty(crawlRule)){
           crawlRule = crawlVo.getCrawlRule();
           crawlRule.setSourceId(crawlVo.getId());
           save(crawlRule);
        }else {
            CrawlRule crawlRule1 = crawlVo.getCrawlRule();
            crawlRule1.setRuleId(crawlRule.getRuleId());
            crawlRule1.setSourceId(crawlRule.getSourceId());
            updateById(crawlRule1);
        }
        redisUtils.delete(RedisConstant.CRAWL_KEY+crawlVo.getId());
    }
}
